import {getCorpCode, getToken, removeCorpCode, removeToken} from "../utils/auth";
import {env} from "../utils/env";

let header = {};
/**
 * @url String 接口地址
 * @data Object 通过body传递的参数
 * @method String 请求方式 默认post
 * @query Object 通过query传参的参数
 * */
const request = function(url, data, method = 'post', query) {
	header = {
		'service-name': env.serviceName,
		'request-environment': env.requestEnvironment,
		'tenant-id': getCorpCode(),
		'content-type': 'application/json'
	};
	if (getToken()) {
		header.Authorization = getToken();
	}
	// 通过query传参的参数
	let str = '';
	if (query && Object.keys(query).length) {
		str = '?';
		let count = 0;
		for (let item in query) {
			if (count) {
				str += '&'
			}
			count++;
			str += `${item}=${encodeURIComponent(query[item])}`
		}
	}
	url+=str;
	return new Promise(function(resolve, reject) {
		wx.request({
			url: `${env.baseUrl}${url}`,
			data: data,
			header: header,
			method: method,
			responseType: method,
			success: (res) => {
				if (res.data.status === 200) {

				} else if (res.data.status === 415) {
					// 被引用
					if (!getApp().globalData.showTipsModal) {
						getApp().globalData.showTipsModal = true;
						wx.showModal({
							title: res.data.message || '服务异常!',
							showCancel: false,
							confirmText: '关闭',
							success: function(res) {
								if (res.confirm) {
									getApp().globalData.showTipsModal = false;
								} else if (res.cancel) {
									getApp().globalData.showTipsModal = false;
								}
							}
						});
					}
				} else if (res.data.status === 401) {
					// 登录失效
					if (!getApp().globalData.showTipsModal) {
						getApp().globalData.showTipsModal = true;
						wx.showModal({
							title: res.data.message || '服务异常!',
							showCancel: true,
							confirmText: '前往登录',
							success: function(res) {
								if (res.confirm) {
									getApp().globalData.showTipsModal = false;
									removeToken();
									removeCorpCode();
									let has = getCurrentPages().find(x => x.route === 'pages/login/index');
									if (!has) {
										wx.navigateTo({
											url: '/pages/login/index'
										});
									}
								} else if (res.cancel) {
									getApp().globalData.showTipsModal = false;
								}
							}
						});
					}
				} else {
					if (!getApp().globalData.showTipsModal) {
						getApp().globalData.showTipsModal = true;
						wx.showModal({
							title: res.data.message || '服务异常!',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									getApp().globalData.showTipsModal = false;
								}
							}
						})
					}

				}
				return resolve(res);
			},
			fail: (err) => {
				return reject(err);
			}
		});
	})

};

export default request;
